package com.tjec.project.system.controller;

import com.tjec.common.constant.UserConstants;
import com.tjec.common.utils.SecurityUtils;
import com.tjec.common.utils.poi.ExcelUtil;
import com.tjec.framework.aspectj.lang.annotation.Log;
import com.tjec.framework.aspectj.lang.enums.BusinessType;
import com.tjec.framework.web.controller.BaseController;
import com.tjec.framework.web.domain.AjaxResult;
import com.tjec.framework.web.page.TableDataInfo;
import com.tjec.project.system.domain.SysDept;
import com.tjec.project.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 组织管理
 *
 * @author tjec
 */
@Api(value = "组织管理Controller", tags = {"组织管理接口"})
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取部门列表
     */
    @ApiOperation("获取部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDept dept) {
        startPage();
        List<SysDept> depts = deptService.selectDeptList(dept);
        return getDataTable(depts);
    }

    /**
     * 导出部门列表
     */
    @ApiOperation("导出部门列表")
    @PreAuthorize("@ss.hasPermi('system:dept:export')")
    @Log(title = "组织管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        ExcelUtil<SysDept> util = new ExcelUtil<SysDept>(SysDept.class);
        return util.exportExcel(depts, "sysDept");
    }

    /**
     * 根据组织guid获取详细信息
     */
    @ApiOperation("根据组织guid获取详细信息")
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{guid}")
    public AjaxResult getInfo(@PathVariable String guid) {
        return AjaxResult.success(deptService.selectDeptById(guid));
    }

    /**
     * 获取部门下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(SysDept dept) {
        List<SysDept> depts = deptService.selectDeptList(dept);
        return AjaxResult.success(deptService.buildDeptTreeSelect(depts));
    }

    /**
     * 加载对应角色部门列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") String roleId) {
        List<SysDept> depts = deptService.selectDeptList(new SysDept());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", deptService.selectDeptListByRoleId(roleId));
        ajax.put("depts", deptService.buildDeptTreeSelect(depts));
        return ajax;
    }

    /**
     * 新增部门
     */
    @ApiOperation("新增部门")
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "组织管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("新增部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        }
        dept.setCreateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        return toAjax(deptService.insertDept(dept));
    }

    /**
     * 修改部门
     */
    @ApiOperation("修改部门")
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysDept dept) {
        if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，部门名称已存在");
        } /*else if (dept.getParentId().equals(dept.getGuid())) {
            return AjaxResult.error("修改部门'" + dept.getDeptName() + "'失败，上级部门不能是自己");
        }*/
        dept.setUpdateBy(SecurityUtils.getLoginUser().getUser().getUserId());
        return toAjax(deptService.updateDept(dept));
    }

    /**
     * 删除部门
     */
    @ApiOperation("删除部门，支持批量删除，多个数据用逗号隔开")
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String guids) {
        /*if (deptService.hasChildByDeptId(guid)) {
            return AjaxResult.error("存在下级部门,不允许删除");
        }*/
        String[] guidArr = guids.split(",");
        for(String guid : guidArr){
            if (deptService.checkDeptExistUser(guid)) {
                return AjaxResult.error("部门存在用户,不允许删除");
            }
            if (deptService.checkProjectExistExecuteDept(guid)) {
                return AjaxResult.error("该部门已被项目所使用,不允许删除");
            }
        }

        return toAjax(deptService.deleteDeptById(guidArr));
    }
}
